/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.gatech.egg.l0cUs.servlet.theme;

import edu.gatech.egg.l0cUs.domain.Configuration;
import edu.gatech.egg.l0cUs.service.ConfigurationDao;
import java.io.File;
import java.io.OutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

/**
 *
 * @author summerspittman
 */
public class ThemeInterceptorServlet extends HttpServlet {

    @Autowired
    private ConfigurationDao configurationDao;

    @Override
    public void init(ServletConfig config) {
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                config.getServletContext());
        //Copy default theme

        File defaultThemeDirectory = new File(config.getServletContext().getRealPath("/static/themes/"));
        File destination = new File(".l0cUs");
        if (!destination.exists()) {
            destination.mkdir();
        }
        try {
            FileUtils.copyDirectory(defaultThemeDirectory, destination);
        } catch (IOException ex) {
            Logger.getLogger(ThemeInterceptorServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Logger.getLogger(ThemeInterceptorServlet.class.getName()).log(Level.FINEST, null, request.getRequestURI());
        Configuration locusConfig = configurationDao.getConfiguration();
        String theme = locusConfig.getTheme();
        File themeFile = new File(".l0cUs/" + theme + "/" + request.getRequestURI().split("/static/")[1]);
        if (!themeFile.exists()) {
            response.sendError(404);
            return;
        } else {
            response.setHeader("Content-disposition", "attachment; filename=" + themeFile.getName());
            if (themeFile.getName().contains(".css")) {
                response.setContentType("text/css");
            } else {
                response.setContentType(javax.activation.MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(themeFile.getName()));
            }
            OutputStream out = response.getOutputStream();
            java.io.InputStream in = null;
            try {
              in = new java.io.BufferedInputStream(new java.io.FileInputStream(themeFile));
              byte[  ] buf = new byte[4 * 1024];  // 4K buffer
              int bytesRead;
              while ((bytesRead = in.read(buf)) != -1) {
                out.write(buf, 0, bytesRead);
              }
            }
            finally {
              if (in != null) in.close(  );
            }


            
            
        }



    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
